package com.yichen.rent.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.yichen.rent.pojo.Newhouse;
import com.yichen.rent.pojo.Oldhouse;
import com.yichen.rent.pojo.Resource;
import com.yichen.rent.response.NewHouseResponse;
import com.yichen.rent.service.NewhouseService;
import com.yichen.rent.service.OldhouseService;
import com.yichen.rent.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yichen.rent.pojo.User;
import com.yichen.rent.service.UserService;

import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import util.JwtUtil;

import javax.servlet.http.HttpSession;

/**
 * 控制器层
 * @author Administrator
 *
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private JwtUtil jwtUtil;

	@Autowired
	private NewhouseService newhouseService;

	@Autowired
	private OldhouseService oldhouseService;

	@Autowired
	private ResourceService resourceService;
	
	/**
	 * 查询全部数据
	 * @return
	 */
	@RequestMapping(method= RequestMethod.GET)
	public Result findAll(){
		return new Result(true,StatusCode.OK,"查询成功",userService.findAll());
	}
	
	/**
	 * 根据ID查询
	 * @param id ID
	 * @return
	 */
	@RequestMapping(value="/{id}",method= RequestMethod.GET)
	public Result findById(@PathVariable String id){
		return new Result(true,StatusCode.OK,"查询成功",userService.findById(id));
	}


	/**
	 * 分页+多条件查询
	 * @param searchMap 查询条件封装
	 * @param page 页码
	 * @param size 页大小
	 * @return 分页结果
	 */
	@RequestMapping(value="/search/{page}/{size}",method=RequestMethod.POST)
	public Result findSearch(@RequestBody Map searchMap , @PathVariable int page, @PathVariable int size){
		Page<User> pageList = userService.findSearch(searchMap, page, size);
		return  new Result(true,StatusCode.OK,"查询成功",  new PageResult<User>(pageList.getTotalElements(), pageList.getContent()) );
	}

	/**
     * 根据条件查询
     * @param searchMap
     * @return
     */
    @RequestMapping(value="/search",method = RequestMethod.POST)
    public Result findSearch( @RequestBody Map searchMap){
        return new Result(true,StatusCode.OK,"查询成功",userService.findSearch(searchMap));
    }
	
	/**
	 * 增加
	 * @param user
	 */
	@RequestMapping(method=RequestMethod.POST)
	public Result add(@RequestBody User user  ){
		Map<String,String> map = new HashMap<>();
		map.put("username",user.getUsername());
		List<User> search = userService.findSearch(map);
		if (!CollectionUtils.isEmpty(search)) {
			return new Result(false,StatusCode.ERROR,"该用户已经注册");
		}
		userService.add(user);
		return new Result(true,StatusCode.OK,"注册成功");
	}
	
	/**
	 * 修改
	 * @param user
	 */
	@RequestMapping(value="/{id}",method= RequestMethod.PUT)
	public Result update(@RequestBody User user, @PathVariable String id ){
		user.setId(id);
		userService.update(user);		
		return new Result(true,StatusCode.OK,"修改成功");
	}
	
	/**
	 * 删除
	 * @param id
	 */
	@RequestMapping(value="/{id}",method= RequestMethod.DELETE)
	public Result delete(@PathVariable String id ){
		userService.deleteById(id);
		return new Result(true,StatusCode.OK,"删除成功");
	}

	/**
	 * 登录
	 * @param user
	 * @return
	 */
	@RequestMapping("/login")
	public Result login(@RequestBody User user, HttpSession session){
		user = userService.login(user.getUsername(), user.getPassword(),user.getUsertype());
		if (user == null) {
			return new Result(false,StatusCode.ERROR, "登录失败,账号或密码不正确");
		}
		String token = jwtUtil.createJWT(user.getId(), user.getUsername(), user.getUsertype());
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("token", token);
		resultMap.put("name", user.getUsername());
		resultMap.put("avatar",user.getAvatar());
		List<String> list = new ArrayList<>();
		String usertype = user.getUsertype();
		if (usertype.equals("系统管理员")) {
			list.add("admin");
		}
		if (usertype.equals("房东")) {
			list.add("house");
		}
		if (usertype.equals("经纪人")) {
			list.add("agent");
		}
		resultMap.put("roles", list);
		resultMap.put("uid", user.getId());
		session.setAttribute("uid",user.getId());
		session.setAttribute("usertype",user.getUsertype());
		return new Result(true,StatusCode.OK, "登录成功", resultMap);
	}

	@RequestMapping(value = "/update/password" ,method = RequestMethod.POST)
	public Result updatePassword(@RequestBody User user){
		userService.updatePassword(user);
		return new Result(true,StatusCode.OK, "修改成功");
	}

	@RequestMapping(value = "/info")
	public Result getInfo(String token){
		Map<String,Object> map = userService.getInfo(token);
		return new Result( true,StatusCode.OK, "获取成功", map);
	}

	@RequestMapping(value = "/logout")
	public Result getInfo(){
		return new Result( true,StatusCode.OK, "退出成功");
	}

	@RequestMapping(value = "/focus/{uid}/{htype}")
	public Result getFocus(@PathVariable("uid") String uid,@PathVariable("htype") String htype) {
		List<String> houseIds = userService.getFocus(uid);
		if(htype.equals("newhouse")) {
			List<Newhouse> list = new ArrayList<>();
			for(String hid : houseIds) {
				Newhouse byId = newhouseService.findById(hid);
				list.add(byId);
			}
			return new Result(true,StatusCode.OK,"查询成功",list);
		}
		if(htype.equals("oldhouse")) {
			List<Oldhouse> list = new ArrayList<>();
			for(String hid : houseIds) {
				Oldhouse byId = oldhouseService.findById(hid);
				list.add(byId);
			}
			return new Result(true,StatusCode.OK,"查询成功",list);
		}
		if(htype.equals("renthouse")) {
			List<Resource> list = new ArrayList<>();
			for(String hid : houseIds) {
				Resource byId = resourceService.findById(hid);
				list.add(byId);
			}
			return new Result(true,StatusCode.OK,"查询成功",list);
		}
		return new Result(false,StatusCode.ERROR,"房源类型错误",null);
	}
}
